package com.xr.handle;

import com.xr.dto.ResultDto;
import com.xr.enums.ResultStatus;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 * @author Arnold Yand
 * @summary 替换掉框架的ResponseBody包装类
 * @time 2018/4/7 11:55
 */
public class ResponseBodyWrapHandle implements HandlerMethodReturnValueHandler {

  private final HandlerMethodReturnValueHandler delegate;

  public  ResponseBodyWrapHandle(HandlerMethodReturnValueHandler delegate){
    this.delegate=delegate;
  }

  @Override
  public boolean supportsReturnType(MethodParameter returnType) {
    return delegate.supportsReturnType(returnType);
  }

  @Override
  public void handleReturnValue(Object returnValue, MethodParameter returnType, ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
    if(returnValue instanceof ResultDto){
      delegate.handleReturnValue(returnValue,returnType,mavContainer,webRequest);
      return;
    }

    ResultStatus resultStatus = null == returnValue ? ResultStatus.SYS_FAILED : ResultStatus.SUCCESS;
    ResultDto result = new ResultDto();
    result.setCode(resultStatus.getCode());
    result.setMessage(resultStatus.getMessage());
    result.setData(returnValue);
    delegate.handleReturnValue(result,returnType,mavContainer,webRequest);
  }
}
